<template>
  <el-table-column
    v-if="showButtons"
    class-name="fu-table-operations"
    :align="align"
    :width="computeWidth"
    v-bind="$attrs"
  >
    <template #header>
      {{ $attrs.label }}
      <!-- <fu-table-column-select v-if="columns" type="dialog" :columns="columns" /> -->
    </template>
    <template #default="{ row }">
      <fu-table-button
        v-for="(btn, i) in defaultButtons"
        :key="i"
        v-bind="btn"
        :disabled="disableButton(btn, row)"
        @click="btn.click(row)"
      />
      <fu-table-more-button
        v-if="moreButtons.length > 0"
        :buttons="moreButtons"
        :row="row"
      />
    </template>
  </el-table-column>
</template>

<script setup lang="ts">
import { computed } from "vue";

type Prop = {
  columns?: any[];
  align?: string;
  width?: string | number;
  minWidth?: string | number;
  ellipsis?: number;
  buttons?: any[];
};
const props = withDefaults(defineProps<Prop>(), {
  columns: () => [],
  align: "center",
  width: undefined,
  minWidth: undefined,
  ellipsis: 1,
  buttons: () => []
});

const showButtons = computed(() => {
  return props.buttons?.filter(btn => btn.show !== false);
});
const hasMore = computed(() => {
  return showButtons.value?.length > props.ellipsis + 1;
});
const defaultButtons = computed(() => {
  return hasMore.value
    ? showButtons.value.slice(0, props.ellipsis)
    : showButtons.value;
});
const moreButtons = computed(() => {
  return hasMore.value ? showButtons.value.slice(props.ellipsis) : [];
});

const computeWidth = computed<string | number>(() => {
  if (props.width) return props.width;
  let buttonsWidth = 20 + defaultButtons.value.length * 38 + 38;
  if (props.minWidth) {
    return buttonsWidth < parseInt(props.minWidth)
      ? props.minWidth
      : buttonsWidth;
  }
  return buttonsWidth;
});

const disableButton = (btn: any, row: any) => {
  return typeof btn.disabled === "function" ? btn.disabled(row) : btn.disabled;
};
</script>
